<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <title>浏览页面</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css"/>
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css"/>
</head>
<body class="pear-container">

<!-- 顶部查询表单 -->
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form top-search-from">
            <div class="layui-form-item">
                <label class="layui-form-label">规则类型</label>
                <div class="layui-input-block">
                    <div name="rule_type" id="rule_type" value=""></div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">规则操作</label>
                <div class="layui-input-block">
                    <div name="rule_action" id="rule_action" value=""></div>
                </div>
            </div>
            <div class="layui-form-item layui-inline">
                <label class="layui-form-label"></label>
                <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                    <i class="layui-icon layui-icon-search"></i>查询
                </button>
                <button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
                    <i class="layui-icon layui-icon-refresh"></i>重置
                </button>
            </div>
            <div class="toggle-btn">
                <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
            </div>
        </form>
    </div>
</div>

<!-- 数据表格 -->
<div class="layui-card">
    <div class="layui-card-body">
        <table id="data-table" lay-filter="data-table"></table>
    </div>
</div>

<!-- 表格顶部工具栏 -->
<script type="text/html" id="table-toolbar">
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add" permission="app.admin.user.insert">
        <i class="layui-icon layui-icon-add-1"></i>新增规则
    </button>
</script>

<!-- 表格行工具栏 -->
<script type="text/html" id="table-bar">
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="app.admin.user.update">编辑</button>
    {{# if(d.is_system !== undefined && d.is_system != 1){ }}
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="app.admin.user.delete">删除</button>
    {{# } }}
</script>

<script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
<script src="/app/admin/component/pear/pear.js"></script>
<script src="/app/admin/admin/js/permission.js"></script>
<script src="/app/admin/admin/js/common.js"></script>
<script>

    // 相关常量
    const PRIMARY_KEY = "id";
    const SELECT_API = "/app/csauto/rules/select";
    const UPDATE_API = "/app/csauto/rules/update";
    const DELETE_API = "/app/csauto/rules/delete";
    const INSERT_URL = "/app/csauto/rules/insert";
    const UPDATE_URL = "/app/csauto/rules/update";


    layui.use(["jquery", "xmSelect", "popup"], function () {
        layui.$.ajax({
            url: "/app/csauto/api/get?name=rule_type",
            dataType: "json",
            success: function (res) {
                let value = layui.$("#rule_type").attr("value");
                let initValue = value ? value.split(",") : [];
                layui.xmSelect.render({
                    el: "#rule_type",
                    name: "rule_type",
                    initValue: initValue,
                    data: res.data,
                    model: {"icon": "hidden", "label": {"type": "text"}},
                    clickClose: true,
                    radio: true,
                });
                if (res.code) {
                    layui.popup.failure(res.msg);
                }
            }
        });

        layui.$.ajax({
            url: "/app/csauto/api/get?name=rule_action",
            dataType: "json",
            success: function (res) {
                let value = layui.$("#rule_action").attr("value");
                let initValue = value ? value.split(",") : [];
                layui.xmSelect.render({
                    el: "#rule_action",
                    name: "rule_action",
                    initValue: initValue,
                    data: res.data,
                    model: {"icon": "hidden", "label": {"type": "text"}},
                    clickClose: true,
                    radio: true,
                });
                if (res.code) {
                    layui.popup.failure(res.msg);
                }
            }
        });
    });

    // 表格渲染
    layui.use(["table", "form", "common", "popup", "util"], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.$;
        let common = layui.common;
        let util = layui.util;
        // 表头参数
        let cols = [
            {
                title: "覆盖站点",
                field: "scope_site_id",
                templet: function (d) {
                    if (d.scope_site_id && d.scope_site_id.length > 0) {
                        let siteIds = [];
                        // 处理不同格式的数据
                        if (Array.isArray(d.scope_site_id)) {
                            siteIds = d.scope_site_id;
                        } else if (typeof d.scope_site_id === 'string') {
                            try {
                                let parsed = JSON.parse(d.scope_site_id);
                                if (Array.isArray(parsed)) {
                                    siteIds = parsed;
                                } else {
                                    siteIds = [d.scope_site_id];
                                }
                            } catch (e) {
                                // 如果JSON解析失败，按逗号分割处理
                                siteIds = d.scope_site_id.split(',');
                            }
                        } else {
                            siteIds = [d.scope_site_id.toString()];
                        }

                        // 映射站点ID到站点名称
                        let siteNames = [];
                        layui.each(siteIds, function (k, v) {
                            // 使用站点ID获取对应的站点名称
                            if (apiResults.sites[v]) {
                                siteNames.push(apiResults.sites[v]);
                            } else {
                                siteNames.push(v);
                            }
                        });

                        return util.escape(siteNames.join(','));
                    } else {
                        return '全部生效';
                    }
                }
            }, {
                title: "规则类型",
                width: 150,
                field: "rule_type",
                templet: function (d) {
                    let field = "rule_type";
                    if (typeof d[field] == "undefined") return "";
                    let items = [];
                    layui.each((d[field] + "").split(","), function (k, v) {
                        items.push(apiResults[field][v] || v);
                    });
                    return util.escape(items.join(","));
                }
            }, {
                title: "规则判断",
                width: 100,
                field: "rule_compare",
                templet: function (d) {
                    let field = "rule_compare";
                    if (typeof d[field] == "undefined") return "";
                    let items = [];
                    layui.each((d[field] + "").split(","), function (k, v) {
                        items.push(apiResults[field][v] || v);
                    });
                    return util.escape(items.join(","));
                }
            }, {
                title: "规则参数",
                field: "rule_value"
            }, {
                title: "规则操作",
                field: "rule_action",
                width: 100,
                templet: function (d) {
                    let field = "rule_action";
                    if (typeof d[field] == "undefined") return "";
                    let items = [];
                    layui.each((d[field] + "").split(","), function (k, v) {
                        items.push(apiResults[field][v] || v);
                    });
                    return util.escape(items.join(","));
                }
            }, {
                title: "规则优先级",
                width: 100,
                field: "sort"
            }, {
                title: "规则备注",
                width: 150,
                field: "notes"
            }, {
                title: "启用",
                field: "rule_status",
                width: 100,
                templet: function (d) {
                    let field = "rule_status";
                    form.on("switch(" + field + ")", function (data) {
                        let load = layer.load();
                        let postData = {};
                        postData[field] = data.elem.checked ? 1 : 0;
                        postData[PRIMARY_KEY] = this.value;
                        $.post(UPDATE_API, postData, function (res) {
                            layer.close(load);
                            if (res.code) {
                                return layui.popup.failure(res.msg, function () {
                                    data.elem.checked = !data.elem.checked;
                                    form.render();
                                });
                            }
                            return layui.popup.success("操作成功");
                        })
                    });
                    let checked = d[field] === 1 ? "checked" : "";
                    return '<input type="checkbox" value="' + util.escape(d[PRIMARY_KEY]) + '" lay-filter="' + util.escape(field) + '" lay-skin="switch" lay-text="' + util.escape('') + '" ' + checked + '/>';
                }
            }, {
                title: "操作",
                toolbar: "#table-bar",
                align: "center",
                fixed: "right",
                width: 130,
            }
        ];

        // 渲染表格
        function render() {
            table.render({
                elem: "#data-table",
                url: SELECT_API,
                page: true,
                cols: [cols],
                skin: "line",
                size: "lg",
                toolbar: "#table-toolbar",
                autoSort: false,
                defaultToolbar: [{
                    title: "刷新",
                    layEvent: "refresh",
                    icon: "layui-icon-refresh",
                }, "filter", "print", "exports"],
                done: function () {
                    layer.photos({photos: 'div[lay-id="data-table"]', anim: 5});
                }
            });
        }

        // 获取表格中下拉或树形组件数据
        let apis = [];
        apis.push(["sites", "/app/csauto/api/get?name=site"]);
        apis.push(["rule_type", "/app/csauto/api/get?name=rule_type"]);
        apis.push(["rule_compare", "/app/csauto/api/get?name=rule_compare"]);
        apis.push(["rule_action", "/app/csauto/api/get?name=rule_action"]);
        let apiResults = {};
        apiResults["sites"] = [];
        apiResults["rule_type"] = [];
        apiResults["rule_compare"] = [];
        apiResults["rule_action"] = [];
        let count = apis.length;
        layui.each(apis, function (k, item) {
            let [field, url] = item;
            $.ajax({
                url: url,
                dateType: "json",
                success: function (res) {
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }

                    function travel(items) {
                        for (let k in items) {
                            let item = items[k];
                            apiResults[field][item.value] = item.name;
                            if (item.children) {
                                travel(item.children);
                            }
                        }
                    }

                    travel(res.data);
                },
                complete: function () {
                    if (--count === 0) {
                        render();
                    }
                }
            });
        });
        if (!count) {
            render();
        }

        // 编辑或删除行事件
        table.on("tool(data-table)", function (obj) {
            if (obj.event === "remove") {
                remove(obj);
            } else if (obj.event === "edit") {
                edit(obj);
            }
        });

        // 表格顶部工具栏事件
        table.on("toolbar(data-table)", function (obj) {
            if (obj.event === "add") {
                add();
            } else if (obj.event === "refresh") {
                refreshTable();
            } else if (obj.event === "batchRemove") {
                batchRemove(obj);
            }
        });

        // 表格顶部搜索事件
        form.on("submit(table-query)", function (data) {
            table.reload("data-table", {
                page: {
                    curr: 1
                },
                where: data.field
            })
            return false;
        });

        // 表格顶部搜索重置事件
        form.on("submit(table-reset)", function (data) {
            table.reload("data-table", {
                where: []
            })
        });

        // 表格排序事件
        table.on("sort(data-table)", function (obj) {
            table.reload("data-table", {
                initSort: obj,
                scrollPos: "fixed",
                where: {
                    field: obj.field,
                    order: obj.type
                }
            });
        });

        // 表格新增数据
        let add = function () {
            layer.open({
                type: 2,
                title: "新增",
                shade: 0.1,
                area: [common.isModile() ? "100%" : "600px", common.isModile() ? "100%" : "600px"],
                content: INSERT_URL
            });
        }

        // 表格编辑数据
        let edit = function (obj) {
            let value = obj.data[PRIMARY_KEY];
            layer.open({
                type: 2,
                title: "修改",
                shade: 0.1,
                area: [common.isModile() ? "100%" : "600px", common.isModile() ? "100%" : "600px"],
                content: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value
            });
        }

        // 删除一行
        let remove = function (obj) {
            return doRemove(obj.data[PRIMARY_KEY]);
        }

        // 删除多行
        let batchRemove = function (obj) {
            let checkIds = common.checkField(obj, PRIMARY_KEY);
            if (checkIds === "") {
                layui.popup.warning("未选中数据");
                return false;
            }
            doRemove(checkIds.split(","));
        }

        // 执行删除
        let doRemove = function (ids) {
            let data = {};
            data[PRIMARY_KEY] = ids;
            layer.confirm("确定删除?", {
                icon: 3,
                title: "提示"
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: DELETE_API,
                    data: data,
                    dataType: "json",
                    type: "post",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        return layui.popup.success("操作成功", refreshTable);
                    }
                })
            });
        }

        // 刷新表格数据
        window.refreshTable = function () {
            table.reloadData("data-table", {
                scrollPos: "fixed",
                done: function (res, curr) {
                    if (curr > 1 && res.data && !res.data.length) {
                        curr = curr - 1;
                        table.reloadData("data-table", {
                            page: {
                                curr: curr
                            },
                        })
                    }
                }
            });
        }
    })

</script>
</body>
</html>
